import pyautogui
import time
import pynput
import pathlib
import os ,sys
import loger
import userlist
from pynput import keyboard

flagExit=False
del_flag=False
log = loger.Logger('心理测评',StreamLevel='debug',FileLevel='info').logger
root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))
picpath=root/"zt.shzenon.cn.pic"
def on_press(key):
    global flagExit
    if key == keyboard.Key.esc:
        log.debug("press ESC")
        flagExit=True
        # sys.exit()
        # return False

# 启动监听器（非阻塞）


def findpic(pic:str,offset_x:int=0,offset_y:int=0)->tuple[int]:
    filepath=picpath/pic
    if  not  filepath.is_file():
        log.error(f"文件 '{filepath}' 不存在")
        return False
    try:
        p = pyautogui.locateOnScreen(str(picpath/pic))
    except pyautogui.ImageNotFoundException as e:
        log.error("图像未找到")
        return False
    (x,y)=pyautogui.center(p)
    log.debug(f"{pic},{x},{y}")
    return (x+offset_x,y+offset_y)

if __name__ == "__main__":
    listener = keyboard.Listener(on_press=on_press)
    listener.start()
    for i in userlist.userlist:
        if flagExit :sys.exit()
        pyautogui.moveTo(findpic("01.png",50))
        pyautogui.click()
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.typewrite(i)
        log.debug(i)
        pyautogui.moveTo(findpic("02.png"))
        pyautogui.click()
        del_flag=False
        for _ in range(15):
            
            if(findpic("03.png")==False):
                time.sleep(1)
            else:
                pyautogui.moveTo(findpic("03.png"))
                pyautogui.click()
                time.sleep(0.5)
                del_flag=True
                pyautogui.moveTo(findpic("04.png"))
                pyautogui.click()
                break
        if(del_flag):
            log.info(f"{i}已删除")
        else:
            log.error(f"{i}未删除")
        time.sleep(1)
    listener.join()